package com.example.papermanagemant.controller;

import com.example.papermanagemant.model.User;
import com.example.papermanagemant.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.crypto.password.PasswordEncoder;




@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/login")
    public String loginForm() {
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String name, @RequestParam String password, Model model) {
        User user = userService.findByName(name);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            return "redirect:/home";  // 登录成功，跳转到首页
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "login";  // 登录失败，返回登录页面
        }
    }


    @GetMapping("/user-info")
    public String userInfo(Model model) {
        // 获取当前用户信息
        User user = userService.findByName("current_user_name"); // 假设当前用户的名字是已知的，可以改成通过session获取
        model.addAttribute("user", user);
        return "user-info";  // 返回个人信息页面
    }

    @PostMapping("/user-info")
    public String updateUserInfo(@RequestParam String name, @RequestParam String password, Model model) {
        User user = userService.findByName(name);
        if (user != null) {
            user.setName(name);
            user.setPassword(passwordEncoder.encode(password)); // 更新密码
            userService.save(user);  // 保存更新后的用户
            model.addAttribute("message", "用户信息更新成功!");
        } else {
            model.addAttribute("error", "用户未找到");
        }
        return "user-info";
    }

    @GetMapping("/register")
    public String registerForm() {
        return "register";
    }

    @PostMapping("/register")
    public String register(@RequestParam String name, @RequestParam String password, Model model) {
        if (userService.findByName(name) != null) {
            model.addAttribute("error", "用户名已存在");
            return "register";
        }
        String encodedPassword = passwordEncoder.encode(password);
        User user = new User();
        user.setName(name);
        user.setPassword(encodedPassword);
        userService.save(user);
        model.addAttribute("message", "注册成功!");
        return "login";
    }
}
